<template>
    <view class="comment-container" :class="{ 'show': show }">
        <view style="height: 25vh;opacity: 0;" @tap="handleClose">
        </view>
        <view style="height: 75vh;background-color: #fff;">
            <!-- 顶部标题栏 -->
            <view class="comment-header">
                <text class="title">{{ totalComments }}条评论</text>
                <text class="close-btn" @tap="handleClose">×</text>
            </view>

            <!-- 评论列表 -->
            <scroll-view class="comment-list" scroll-y @scrolltolower="loadMoreComments" v-if="comments.length > 0">
                <view class="comment-item" v-for="(comment, index) in comments" :key="index">
                    <view class="comment-user">
                        <image class="user-avatar" :src="comment.headimg" mode="aspectFill"></image>
                        <view class="user-info">
                            <view class="user-name">{{ comment.nickname }}{{ comment.mid == 0 ? '（作者）' : '' }}
                            </view>
                            <view v-if="comment.content" class="comment-content">{{ comment.content }}</view>
                            <view class="comment-extra">
                                <!-- <text v-if="comment.tag" class="user-tag">{{ comment.tag }}</text> -->
                                <text class="comment-date">{{ comment.createtime }}</text>
                                <text class="reply-btn" @tap="handleReply(comment)">回复</text>
                                <text class="delete-btn" @tap="handleDelete(comment)"
                                    v-if="comment.mid == mid">删除</text>
                            </view>

                            <view v-if="comment.sub_list && comment.sub_list.length > 0" class="reply-list">
                                <view v-for="(reply, replyIndex) in comment.sub_list" :key="replyIndex"
                                    v-if="replyIndex === 0 || comment.showAllReplies" class="reply-item">
                                    <image class="reply-avatar" :src="reply.headimg" mode="aspectFill"></image>
                                    <view class="reply-info">
                                        <view class="reply-name">{{ reply.nickname }}{{ reply.mid == 0 ? '（作者）' :
                                            '' }}</view>
                                        <view class="reply-content">
                                            <text class="reply-to" v-if="reply.replyTo">回复：
                                                <!-- {{ reply.replyTo}}： -->
                                            </text>
                                            {{ reply.content }}
                                        </view>
                                        <view class="reply-extra">
                                            <text class="reply-date">{{ reply.createtime }}</text>
                                            <!-- <text class="reply-btn" @tap="handleReply(reply, comment)">回复</text> -->
                                            <text class="delete-btn" @tap="handleDelete(reply)"
                                                v-if="reply.mid == mid">删除</text>
                                        </view>
                                    </view>
                                </view>
                                <view v-if="comment.sub_list.length > 1" class="expand-btn"
                                    @tap="toggleReplies(comment)">
                                    <text :style="{ color: t('color1') }" class="expand-text">{{
                                        comment.showAllReplies
                                            ? '收起' :
                                            `展开${comment.sub_list.length - 1}条回复` }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <nomore text="没有更多内容了" v-if="nomore"></nomore>
            </scroll-view>

            <view class="comment-tip" v-if="loaddata">
                {{ commentTip }}
            </view>

            <!-- 底部评论输入框 -->
            <view class="comment-input-wrapper">
                <view class="comment-input-box">
                    <view v-if="replyTo" class="reply-tag" @tap="clearReply">
                        <text>@{{ replyTo.username }}</text>
                        <text class="close-icon">×</text>
                    </view>
                    <input class="comment-input" type="text" v-model="commentText" :placeholder="getPlaceholder" />
                    <view :style="{ color: t('color1') }" class="send-btn" @tap="sendComment">发送</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
var app = getApp();
export default {
    props: {
        show: {
            type: Boolean,
            default: false
        },
        listid: {
        },
        id: {

        }
    },
    data() {
        return {
            static_url: app.globalData.static_url,
            mid: app.globalData.mid,
            totalComments: 0,
            commentText: '',
            inputFocus: false,
            comments: [
                // {
                //     id: 1,
                //     username: '古苏',
                //     avatar: '../static/img/album.png',
                //     content: '雷总，我们一般早上吃苦',
                //     time: '11小时前·河北',
                //     likes: '19.7万',
                //     replies: []
                // },
                // {
                //     id: 2,
                //     username: '尼古拉斯',
                //     avatar: '../static/img/album.png',
                //     content: '只有早上吃吗？中午晚上不吃吗？😂',
                //     time: '9小时前·山东',
                //     likes: '2.4万',
                //     replies: []
                // },
                // {
                //     id: 3,
                //     username: '醒醒成精记',
                //     avatar: '../static/img/album.png',
                //     content: '中午吃亏，下午吃瘪，晚上吃饼😭',
                //     time: '9小时前·广东',
                //     likes: '2.9万',
                //     replies: []
                // }
            ],
            episodes: new Array(80).fill({}),//选集列表
            replyTo: null,//回复对象
            commentText: '',//评论内容
            commentNumber: 0,//评论数量
            commentTip: '评论加载中...',
            loaddata: false,
            nomore: false,
            pagenum: 1,
            limit: 10,
            listid: 0,
            id: 0,
        }
    },
    watch: {
        show(newVal, oldVal) {
            if (newVal === true && oldVal === false) {
                console.log('show', this.listid, app.globalData.mid);
                this.mid = app.globalData.mid;
                this.getComment(this.listid)
            } else {
                this.init();
            }
        }
    },
    computed: {
        getPlaceholder() {
            return this.replyTo ? '回复 ' + this.replyTo.username : '说点什么...';
        }
    },
    onload() {
    },
    methods: {
        init() {
            this.comments = []
            this.totalComments = 0;
            this.pagenum = 1;
        },
        // 获取评论
        getComment(vid) {
            let that = this;
            that.loaddata = true;
            that.nomore = false;
            app.get('VideoCenter/evaluateList?id=' + vid + '&page=' + that.pagenum + '&limit=' + that.limit, {}, function (res) {
                if (res && res.status == 200) {
                    that.totalComments = res.data.evaluations ? res.data.evaluations : 0;
                    // if (!res.data.list || res.data.list.length == 0) {
                    //     that.loaddata = true;
                    //     that.commentTip = '暂无评论';
                    //     return;
                    // }
                    if (that.pagenum == 1) {
                        that.comments = res.data.list.map(comment => ({
                            ...comment,
                            showAllReplies: false
                        }));
                        if (res.data.list.length == 0) {
                            that.commentTip = '暂无评论';
                            that.loaddata = true;
                            that.nomore = false;
                        }
                    } else {
                        if (res.data.list.length == 0) {
                            that.nomore = true;
                            that.loaddata = false;
                        } else {
                            let cl = res.data.list.map(comment => ({
                                ...comment,
                                showAllReplies: false
                            }));
                            var datalist = that.comments;
                            var newdata = datalist.concat(cl);
                            that.comments = newdata;
                        }
                    }
                } else {
                    app.error(res.msg);
                }
            });
        },

        loadMoreComments: function () {
            console.log("滚动到底部")
            if (!this.nomore) {
                this.pagenum = this.pagenum + 1;
                this.getComment(this.listid);
            } else {
                app.error('没有更多内容了');
            }
        },

        handleClose() {
            this.$emit('close');
        },

        handleReply(user, parentComment = null) {
            this.replyTo = {
                username: user.nickname,
                parentComment: parentComment,
                uid: user.id
            };
            // 自动聚焦输入框
            this.$nextTick(() => {
                const query = uni.createSelectorQuery().in(this);
                query.select('.comment-input').boundingClientRect(data => {
                    if (data) {
                        uni.pageScrollTo({
                            scrollTop: data.top,
                            duration: 300
                        });
                    }
                }).exec();
            });
        },
        handleDelete(comment) {
            let that = this;
            uni.showModal({
                title: '提示',
                content: "是否确认删除评论？",
                success(res) {
                    if (res.confirm) {
                        app.showLoading('删除中...');
                        app.post('VideoCenter/evaluateDel', { video_center_content_id: that.listid, video_center_evaluate_id: comment.id, video_center_list_id: that.id }, function (res) {
                            if (res && res.status == 200) {
                                app.success('删除成功');
                                that.pagenum = 1;
                                that.getComment(that.listid);
                                app.showLoading(false);
                            } else {
                                app.error("删除失败:" + res.msg);
                                app.showLoading(false);
                            }
                        });
                    } else if (res.cancel) {
                    }
                }
            });
        },
        clearReply() {
            this.replyTo = null;
        },
        sendComment() {
            let that = this;
            if (!that.commentText.trim()) {
                uni.showToast({
                    title: '请输入评论内容',
                    icon: 'none'
                });
                return;
            }
            let pid = that.replyTo ? that.replyTo.uid : null
            app.showLoading('发送中...');
            app.post('VideoCenter/evaluateAdd', { video_center_content_id: that.listid, content: that.commentText, parent_id: pid }, function (res) {
                if (res && res.status == 200) {
                    app.showLoading(false);
                    app.success('评论成功,请等待审核');
                    // 清空输入框和回复状态
                    that.commentText = '';
                    // that.commentNumber = that.commentNumber + 1;
                    that.clearReply();
                } else {
                    app.showLoading(false);
                    app.error("评论失败:" + res.msg);
                }
            });

            return;
            // 构建评论数据
            const commentData = {
                content: this.commentText,
                date: new Date().toISOString().split('T')[0],
                username: '当前用户', // 这里应该是实际的用户信息
                avatar: 'https://example.com/avatar.jpg' // 这里应该是实际的用户头像
            };

            if (this.replyTo) {
                // 处理回复逻辑
                if (this.replyTo.parentComment) {
                    // 回复评论的回复
                    if (!this.replyTo.parentComment.sub_list) {
                        this.replyTo.parentComment.sub_list = [];
                    }
                    this.replyTo.parentComment.sub_list.push({
                        ...commentData,
                        replyTo: this.replyTo.username
                    });
                } else {
                    // 直接回复评论
                    this.comments.unshift({
                        ...commentData,
                        sub_list: []
                    });
                }
            } else {
                // 发表新评论
                this.comments.unshift({
                    ...commentData,
                    sub_list: []
                });
            }

            // 清空输入框和回复状态
            this.commentText = '';
            this.clearReply();

            uni.showToast({
                title: '发送成功',
                icon: 'success'
            });
        },
        toggleReplies(comment) {
            comment.showAllReplies = !comment.showAllReplies;
        },
    }
}
</script>

<style lang="scss" scoped>
.comment-container {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100vh;
    // background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    transform: translateY(100%);
    transition: transform 0.3s ease-out;
    z-index: 999;

    &.show {
        transform: translateY(0);
    }

    .comment-header {
        padding: 30rpx;
        border-bottom: 2rpx solid #f5f5f5;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        border-radius: 10rpx 10rpx 0 0;
        box-shadow: 0rpx 2rpx 6rpx 0rpx rgba(0, 0, 0, 0.3);

        .title {
            font-size: 32rpx;
            font-weight: bold;
            color: #333;
        }

        .close-btn {
            position: absolute;
            right: 30rpx;
            font-size: 40rpx;
            color: #999;
            padding: 10rpx;
        }
    }

    .comment-list {
        height: calc(75vh - 180rpx);
        padding: 0 30rpx;

        .comment-item {
            padding: 30rpx 0;
            border-bottom: 1rpx solid #f5f5f5;

            .comment-user {
                display: flex;
                align-items: flex-start;
                position: relative;

                .user-avatar {
                    width: 80rpx;
                    height: 80rpx;
                    border-radius: 50%;
                    margin-right: 20rpx;
                }

                .user-info {
                    flex: 1;

                    .user-name {
                        font-size: 28rpx;
                        color: #333;
                        margin-bottom: 8rpx;
                    }

                    .comment-content {
                        font-size: 28rpx;
                        color: #333;
                        margin: 16rpx 0;
                        line-height: 1.5;
                    }

                    .comment-extra {
                        display: flex;
                        align-items: center;

                        .comment-date {
                            font-size: 24rpx;
                            color: #999;
                        }

                        .reply-btn {
                            font-size: 24rpx;
                            color: #000000;
                            margin-left: 15rpx;
                            background-color: #f1f1f1;
                            padding: 6rpx;
                            border-radius: 8rpx;
                        }

                        .delete-btn {
                            font-size: 24rpx;
                            color: red;
                            margin-left: 20rpx;
                            background-color: #f1f1f1;
                            padding: 6rpx;
                            border-radius: 8rpx;
                        }
                    }

                    .reply-list {
                        background: #f8f8f8;
                        border-radius: 8rpx;
                        margin-top: 16rpx;
                        padding: 16rpx;

                        .reply-item {
                            display: flex;
                            margin-bottom: 16rpx;

                            &:last-child {
                                margin-bottom: 0;
                            }


                            .reply-avatar {
                                width: 40rpx;
                                height: 40rpx;
                                border-radius: 50%;
                                margin-right: 12rpx;
                            }

                            .reply-info {
                                flex: 1;

                                .reply-name {
                                    font-size: 24rpx;
                                    color: #666;
                                    margin-bottom: 4rpx;
                                }

                                .reply-content {
                                    font-size: 26rpx;
                                    color: #333;
                                    line-height: 1.4;

                                    .reply-to {
                                        color: #ba1f25;
                                        margin-right: 4rpx;
                                    }
                                }

                                .reply-extra {
                                    margin-top: 4rpx;


                                    .reply-date {
                                        font-size: 22rpx;
                                        color: #999;
                                    }

                                    .delete-btn {
                                        font-size: 24rpx;
                                        color: red;
                                        margin-left: 20rpx;
                                        background-color: #f1f1f1;
                                        padding: 6rpx;
                                        border-radius: 8rpx;
                                    }
                                }
                            }


                        }

                        .expand-text {
                            font-size: 24rpx;
                            color: #ba1f25;
                            cursor: pointer;
                        }
                    }
                }
            }
        }
    }

    .comment-tip {
        padding: 30rpx 0;
        text-align: center;
        color: #999;
        font-size: 28rpx;
    }

    .comment-input-wrapper {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        background: #fff;
        padding: 20rpx 30rpx;
        box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
        z-index: 100;
        padding-bottom: calc(20rpx + env(safe-area-inset-bottom));

        .comment-input-box {
            display: flex;
            align-items: center;
            background: #f5f5f5;
            border-radius: 36rpx;
            padding: 0 24rpx;
            min-height: 72rpx;

            .reply-tag {
                display: inline-flex;
                align-items: center;
                background: #e8f3ff;
                padding: 4rpx 9rpx;
                border-radius: 18rpx;
                margin-right: 12rpx;
                font-size: 30rpx;
                color: #ba1f25;

                .close-icon {
                    margin-left: 8rpx;
                    font-size: 32rpx;
                    color: #999;
                }
            }



            .comment-input {
                flex: 1;
                height: 72rpx;
                font-size: 28rpx;
                background: transparent;
            }

            .send-btn {
                padding: 0 24rpx;
                height: 72rpx;
                line-height: 72rpx;
                color: #ba1f25;
                font-size: 28rpx;
            }

            .expand-btn {
                margin-top: 16rpx;
                padding: 8rpx 0;
            }

            .expand-text {
                font-size: 24rpx;
                color: #ba1f25;
                cursor: pointer;
            }

            .follow-btn {
                background: #ba1f25;
                color: #fff;
                padding: 0rpx 12rpx;
                border-radius: 10rpx;
                font-size: 24rpx;
                height: 40rpx;
                line-height: 40rpx;
                margin-left: 10rpx;
            }
        }
    }
}
</style>
